package com.wtwd.wtwddevice.listener.appMsg;


import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.AnswerStateEnum;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.AppProtocol;
import com.wtwd.wtwddevice.listener.deviceServerMsg.handler.IMsgHandler;
import com.wtwd.wtwddevice.mq.PushAppMsgService;
import com.wtwd.wtwddevice.service.IDeviceService;
import com.wtwd.wtwddevice.service.IDeviceStatusService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录协议处理
 * 1.设备上线,更新设备信息
 * 2.回复设备
 */

@MsgType(MsgTypeEnum.APP_LOGIN)
@Component
public class AppLoginHandlerImpl implements IMsgHandler {

    @Resource
    private IDeviceService deviceService;

    @Resource
    private PushAppMsgService msgService;

    @Resource
    private IDeviceStatusService deviceStatusService;


    @Override
    public void handleMsg(MessageBase messageBase) {
        AppProtocol protocol = messageBase.getAppProtocol();
        AnswerStateEnum anEnum = AnswerStateEnum.ABNORMAL;
        if (deviceService.appLogin(messageBase.getForm(), protocol.getImei())) {
            Long deviceId = deviceService.getDeviceIdByImei(protocol.getImei());
            boolean onlineState = deviceStatusService.getDeviceOnlineState(deviceId);
            if (onlineState) {//在线则回复正常状态
                anEnum = AnswerStateEnum.NORMAL;
            }
        }
        AppProtocol data = AppProtocol.builder()
                .imei(protocol.getImei())
                .cmdName(MsgTypeEnum.APP_LOGIN.getCmdName())
//                .data(new AppLoginVo(anEnum.getState()))
                .state(anEnum.getState())
                .build();
        msgService.pushToDevice(messageBase.getForm(),
                         MessageBase.builder()
                        .appProtocol(data)
                        .build()
        );
    }

}
